<script>
import {addNewUserInfo, disabledUser, fetchList, updateUserInfos} from '@/api/user'
import {mapGetters} from 'vuex'
import router from '@/router'
import {getToken} from '@/utils/auth'

export default {
  data() {
    return {
      searchContent: '',
      page: 1,
      pageSize: 20,
      pageTotal: 0,
      userList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      userInfo: {
        username: '',
        password: '',
        name: '',
        tel: '',
        mail: '',
        inOnline: '',
        introductd: '',
        age: '',
        job: '',
        companys: '',
        sexs: '未知',
        bornDate: '',
        headimgurl: '',
        isDeleted: '',
        isEnabled: '',
        inputTime: '',
        updateTime: '',
        roles: '',
        identificationCard: ''
      },
      formLabelWidth: '80px',
      educationOptions: [],
      isShow: false,
      headerImgFiles: [],
      sexOptions: [
        {
          label: '男',
          value: '男'
        },
        {
          label: '女',
          value: '女'
        },
        {
          label: '未知',
          value: '未知'
        }
      ],
      searchRadio: '不限', // 默认为不限
      roleOptions: [
        {
          label: 'admin',
          value: 'admin'
        },
        {
          label: '患者',
          value: '患者'
        },
        {
          label: '医生',
          value: '医生'
        }
      ],
      searchRoles: [
        {
          label: 'admin',
          value: 'admin'
        },
        {
          label: '患者',
          value: '患者'
        },
        {
          label: '医生',
          value: '医生'
        },
        {
          label: '不限',
          value: '不限'
        }
      ]
    }
  },
  mounted() {
    this.getData()
  },
  created() {
    console.log(this.roles)
    if (!this.roles.includes('admin')) {
      router.push('/401')
      setTimeout(() => {
        router.push('/')
      })
    }
  },
  methods: {
    getToken,
    getData() {
      fetchList(this.page, this.pageSize, this.searchContent, this.searchRadio)
        .then(res => {
          console.log(res)
          const msg = res.message
          this.userList = msg.list
          this.pageTotal = msg.total
        })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
    },
    reset() {
      this.searchContent = ''
      this.page = 1
      this.pageSize = 20
      this.pageTotal = 0
      this.getData()
    },
    resetFormData() {
      this.userInfo = {
        userPk: '',
        username: '',
        password: '',
        name: '',
        tel: '',
        mail: '',
        inOnline: '',
        introductd: '',
        age: '',
        sexs: '',
        bornDate: '',
        headimgurl: '',
        isDeleted: '',
        isEnabled: '',
        inputTime: '',
        updateTime: '',
        roles: '',
        identificationCard: ''
      }
      this.headerImgFiles = []
    },
    created() {
      this.resetFormData()
      this.isShow = true
    },
    handleError(err, file, fileList) {
      console.log(err)
      this.$message({
        message: file.name + '上传失败',
        type: 'error'
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handlePictureCardPreviewImg(url) {
      this.dialogImageUrl = url
      this.dialogVisible = true
    },
    handleRemoveImg(file, fileList) {
      // console.log(file, fileList)
    },
    handleSuccessImg(response, file, fileList) {
      // console.log(response)
      const url = response.message
      this.userInfo.headimgurl = url
      this.headerImgFiles = [{
        name: file.name,
        url: url
      }]
    },
    submitInfo() {
      const data = {
        password: this.userInfo.password,
        userPk: this.userInfo.userPk,
        username: this.userInfo.username,
        name: this.userInfo.name,
        tel: this.userInfo.tel,
        mail: this.userInfo.mail,
        bornDate: this.userInfo.bornDate,
        sexs: this.userInfo.sexs,
        headimgurl: this.headerImgFiles[0].url ? this.headerImgFiles[0].url : '',
        identificationCard: this.userInfo.identificationCard,
        roles: this.userInfo.roles
      }
      console.log(data)
      if (data.userPk === '') {
        addNewUserInfo(data)
          .then(res => {
            console.log(res)
            if (!res.success) {
              this.$message({
                type: 'error',
                message: res.message
              })
            } else {
              this.$message({
                type: 'success',
                message: '添加成功'
              })
            }
          })
      } else {
        updateUserInfos(data)
          .then(res => {
            console.log(res)
            if (!res.success) {
              this.$message({
                type: 'error',
                message: res.message
              })
            } else {
              this.$message({
                type: 'success',
                message: '更新成功'
              })
            }
          })
      }
      setTimeout(() => {
        this.isShow = false
        this.getData()
      }, 150)
    },
    editInfo(row) {
      console.log(row)
      this.userInfo = {
        userPk: row.userPk,
        username: row.username,
        name: row.name,
        tel: row.tel,
        mail: row.mail,
        bornDate: row.bornDate,
        roles: row.roles,
        sexs: `${row.sexs == null ? '未知' : row.sexs}`,
        rolesFk: `${row.rolesFk == null ? '2' : row.rolesFk}`,
        identificationCard: row.identificationCard
      }
      this.headerImgFiles = [{
        name: 'headimg',
        url: row.headimgurl
      }]
      this.isShow = true
    },
    isDisabled(row) {
      console.log(row)
      disabledUser(row.userPk, row.isEnabled === 0 ? 1 : 0)
        .then(res => {
          console.log(res)
          if (!res.success) {
            this.$message({
              type: 'error',
              message: res.message
            })
          } else {
            this.$message({
              type: 'success',
              message: row.isEnabled === 0 ? '恢复成功' : '禁用成功'
            })
            this.getData()
          }
        })
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  }
}
</script>

<template>
  <div class="app-container">
    <el-dialog :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" alt="" width="100%">
    </el-dialog>
    <el-dialog :visible.sync="isShow" title="用户信息">
      <el-form :model="userInfo">
        <el-row>
          <el-col :md="12" :sm="12" :xs="24">
            <el-form-item :label-width="formLabelWidth" label="用户账号">
              <el-input v-model="userInfo.username" autocomplete="off" placeholder="请输入用户账号"/>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="12" :xs="24">
            <el-form-item :label-width="formLabelWidth" label="昵称">
              <el-input v-model="userInfo.name" placeholder="请输入昵称"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label-width="formLabelWidth" label="电话">
          <el-input v-model="userInfo.tel" autocomplete="off" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="密码">
          <el-input
            v-model="userInfo.password"
            :placeholder="userInfo.userPk ? '如果设置了，将会更新新的密码' : '设置你的密码'"
            autocomplete="off"
            type="password"
          />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="电子邮箱">
          <el-input v-model="userInfo.mail" autocomplete="off" placeholder="请输入电子邮箱"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="身份证">
          <el-input v-model="userInfo.identificationCard" autocomplete="off" placeholder="请输入身份证"/>
        </el-form-item>
        <el-row>
          <el-col :md="12" :sm="12" :xs="24">
            <el-form-item :label-width="formLabelWidth" label="出生日期">
              <el-date-picker
                v-model="userInfo.bornDate"
                placeholder="请选择出生日期"
                type="date"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="12" :sm="12" :xs="24">
            <el-form-item :label-width="formLabelWidth" label="身份">
              <el-select v-model="userInfo.roles" filterable placeholder="请选择身份">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="12" :xs="24">
            <el-form-item :label-width="formLabelWidth" label="性别">
              <el-select
                v-model="userInfo.sexs"
                filterable
                placeholder="请选择性别"
              >
                <el-option
                  v-for="item in sexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label-width="formLabelWidth" label="头像">
          <el-upload
            :file-list="headerImgFiles"
            :headers="{
              token:getToken()
            }"
            :limit="1"
            :on-error="handleError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemoveImg"
            :on-success="handleSuccessImg"
            action="/api/upload/img"
            list-type="picture-card"
          >
            <i class="el-icon-plus"/>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="submitInfo">确 定</el-button>
      </div>
    </el-dialog>
    <div class="d-flex ai-center jc-end">
      <el-select v-model="searchRadio" placeholder="请选择角色" style="margin-right: 20px;">
        <el-option
          v-for="item in searchRoles"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-input
        v-model="searchContent"
        placeholder="请输入用户名称"
        prefix-icon="el-icon-search"
        style="max-width: 220px;margin-right: 10px;"
      />
      <el-button type="primary" @click="getData">搜索</el-button>
      <el-button type="primary" @click="reset">重置</el-button>
      <el-button type="primary" @click="created">新增</el-button>
    </div>
    <el-table :data="userList" height="75vh" style="width: 100%;margin-top: 20px">
      <el-table-column label="账号" prop="username" width="200"/>
      <el-table-column label="头像" width="120">
        <template slot-scope="scope">
          <div @click="handlePictureCardPreviewImg(scope.row.headimgurl)">
            <el-avatar :src="scope.row.headimgurl" shape="square" size="medium"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="昵称" prop="name" width="100"/>
      <el-table-column label="性别" prop="sexs" width="120"/>
      <el-table-column label="身份" prop="roles" width="120"/>
      <el-table-column label="电话" prop="tel" width="180"/>
      <el-table-column label="邮箱" prop="mail" width="230"/>
      <el-table-column label="出生日期" prop="bornDate" width="180"/>
      <el-table-column label="是否禁用" width="120">
        <template slot-scope="scope">
          {{ scope.row.isEnabled == 1 ? '正常' : '禁用' }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <div class="d-flex flex-wrap">
            <el-button type="primary" @click="editInfo(scope.row)">编辑</el-button>
            <el-button type="danger" @click="isDisabled(scope.row)">{{ scope.row.isEnabled == 1 ? '禁用' : '恢复' }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="d-flex jc-end">
      <el-pagination
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[20, 50, 100, 200]"
        :total="pageTotal"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>

</style>
